package cn.jnetty.ioc.definition;

import cn.jnetty.api.annotation.JAutowired;
import cn.jnetty.api.annotation.JResource;
import cn.jnetty.api.annotation.JValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/4/3 17:46
 * 描述：
 */
public abstract class JDefaultBeanDefinition {
    protected Annotation annotation;
    protected Class<?> clazz;

    public JDefaultBeanDefinition(Annotation annotation, Class<?> clazz) {
        this.annotation = annotation;
        this.clazz = clazz;
    }
    protected final Logger log = LoggerFactory.getLogger(JDefaultBeanDefinition.class);
    protected abstract void init();
    public static void autowired(Object server) {
        //获取所有字段
        //是否有JAutowired或者JValue注解
        Field[] fields = server.getClass().getDeclaredFields();
        Class c = server.getClass().getSuperclass();
        while (c != Object.class) {
            int srcLength = fields.length;
            Field[] superFields = c.getDeclaredFields();
            fields = Arrays.copyOf(fields, fields.length + superFields.length);
            System.arraycopy(superFields, 0, fields, srcLength, superFields.length);
            c = c.getSuperclass();
        }
        for (Field field : fields) {
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                Class<? extends Annotation> annotationType = annotation.annotationType();
                if (annotationType == JAutowired.class) {
                    JAutowired scan = JAutowired.class.cast(annotation);
                    new JAutowiredBeanDefinition(scan, field, server);
                } else if (annotationType == JValue.class) {
                    JValue scan = JValue.class.cast(annotation);
                    new JValueBeanDefinition(scan, server, field);
                }else if(annotationType == JResource.class){
                    JResource scan = JResource.class.cast(annotation);
                    new JResourceBeanDefinition(scan, field, server);
                }
            }
        }
    }
    public static void autowired(){
        List<Object> list = JDefaultBeanDefinitionFactory.getInstance().getList();
        for (Object o : list) {
            autowired(o);
        }
    }

}
